$(function () {

    new AjaxUpload('#upload', {
        action: baseURL + "noc/nocmember/upload",
        name: 'file',
        autoSubmit:true,
        responseType:"json",
        onSubmit:function(file, extension){
            if (!(extension && /^(xls|xlsx)$/.test(extension.toLowerCase()))){
                alert('只支持xls、xlsx格式的图片！');
                return false;
            }
        },
        onComplete : function(file, r){
            if(r.code == 0){
                alert("导入成功");
                vm.reload();
            }else{
                alert(r.msg);
            }
        }
    });

});

var vm = new Vue({
	el:'#rrapp',
	data:{
		showList: true,
		title: null,
		nocMember: {},
        total:0,
        signCount:0,
        showCard: false,
        showUpd: false,
        templates:[],
        templateId: "",
        lys:[],
        ly:"",
        colObject:{},
        memberId: '',
        nocLabels:[],
        selectedLabels:[]
	},
    watch: {
        templateId (val,oldval){
            this.getTemplateTitle();
            this.memberCount();
            this.getLys();
        },
    },
    mounted() {
        this.$refs.col1.focus();
        //this.$refs.col2.focus();
        //this.memberCount();
    },
    created(){
        this.getTemplates();
        this.getLabels();
        //this.getLys();
    },

	methods: {
        getPageSize: function (){
            var winW, winH;
            if(window.innerHeight) {
                winW = window.innerWidth;
                winH = window.innerHeight;
            } else if (document.documentElement && document.documentElement.clientHeight) {
                winW = document.documentElement.clientWidth;
                winH = document.documentElement.clientHeight;
            } else if (document.body) { // other
                winW = document.body.clientWidth;
                winH = document.body.clientHeight;
            }
            return {WinW:winW, WinH:winH};
        },
        query: function () {
            this.memberCount();
			vm.reload();
		},
		add: function(){
			vm.showList = false;
			vm.title = "新增";
			vm.nocMember = {};
		},
		update: function (event) {
			var id = getSelectedRow();
			if(id == null){
				return ;
			}
			vm.showList = false;
            vm.showUpd = true;
            vm.title = "修改";

            //配对标签取消选择
            $("input[type='checkbox'][id='cklabel']").removeAttr("checked");//取消全选
            vm.getInfo(id)

		},
		saveOrUpdate: function (event) {
		    $('#btnSaveOrUpdate').button('loading').delay(1000).queue(function() {
                var url = vm.nocMember.id == null ? "noc/nocmember/save" : "noc/nocmember/update";

                var labelIds = "";
                $("input[type='checkbox'][id='cklabel']").each(function() {
                    if ($(this).is(":checked")) {
                        labelIds += $(this).val()+",";
                    }
                });
                vm.nocMember.labelIds = labelIds;

                $.ajax({
                    type: "POST",
                    url: baseURL + url,
                    contentType: "application/json",
                    data: JSON.stringify(vm.nocMember),
                    success: function(r){
                        if(r.code === 0){
                             layer.msg("操作成功", {icon: 1});
                             //清空条件
                             vm.memberId = vm.nocMember.id;
                             vm.nocMember = {};
                             vm.reload();
                             $('#btnSaveOrUpdate').button('reset');
                             $('#btnSaveOrUpdate').dequeue();
                        }else{
                            layer.alert(r.msg);
                            $('#btnSaveOrUpdate').button('reset');
                            $('#btnSaveOrUpdate').dequeue();
                        }
                    }
                });
			});
		},
		del: function (event) {
			var ids = getSelectedRows();
			if(ids == null){
				return ;
			}
			var lock = false;
            layer.confirm('确定要删除选中的记录？', {
                btn: ['确定','取消'] //按钮
            }, function(){
               if(!lock) {
                    lock = true;
		            $.ajax({
                        type: "POST",
                        url: baseURL + "noc/nocmember/delete",
                        contentType: "application/json",
                        data: JSON.stringify(ids),
                        success: function(r){
                            if(r.code == 0){
                                layer.msg("操作成功", {icon: 1});
                                $("#jqGrid").trigger("reloadGrid");
                            }else{
                                layer.alert(r.msg);
                            }
                        }
				    });
			    }
             }, function(){
             });
		},
		getInfo: function(id){
			$.get(baseURL + "noc/nocmember/info/"+id, function(r){
                vm.nocMember = r.nocMember;
                vm.selectedLabels = r.labels;
                console.log(r.labels)
                vm.getLabels();
            });
		},
        closeLayer: function () {
            vm.showList = true;
            vm.showCard = false;
            vm.showUpd = false;
            vm.nocMember = {};
        },
		reload: function (event) {
			vm.showList = true;
            vm.showCard = false;
            vm.showUpd = false;
			var page = $("#jqGrid").jqGrid('getGridParam','page');
			$("#jqGrid").jqGrid('setGridParam',{
                postData:{'col1': vm.nocMember.col1,'col2': vm.nocMember.col2,'ly': vm.ly,'templateId':vm.templateId},
                page:page
            }).trigger("reloadGrid");
		},
        sign: function (event) {
            var ids = getSelectedRows();
            if(ids == null){
                return ;
            }
            var lock = false;
            layer.confirm('确定要签到选中的记录？', {
                btn: ['确定','取消'] //按钮
            }, function(){
                if(!lock) {
                    lock = true;
                    $.ajax({
                        type: "POST",
                        url: baseURL + "noc/nocmember/sign",
                        contentType: "application/json",
                        data: JSON.stringify(ids),
                        success: function(r){
                            if(r.code == 0){
                                layer.msg("签到成功", {icon: 1});
                                $("#jqGrid").trigger("reloadGrid");
                            }else{
                                layer.alert(r.msg);
                            }
                        }
                    });
                }
            }, function(){
            });
        },
        memberCount: function () {
            $.get(baseURL + "noc/nocmember/memberCount?tid="+vm.templateId+"&ly="+vm.ly, function(r){
                console.log(r);
                vm.total = r.total;
                vm.signCount = r.sign;
            });
        },
        sendCard: function () {
            vm.showCard = true;
            vm.showUpd = false;
            vm.showList = false;
            vm.title = "发放入场证件";
            vm.nocMember = {};

            //var ids = getSelectedRows();
            var grid = $("#jqGrid");
            var ids = grid.getGridParam("selarrrow");
            console.log("------");
            console.log(ids);
            if(ids!=null && ids.length>0){
                var rowData = $("#jqGrid").jqGrid('getRowData',ids[0]);
                vm.nocMember.id = rowData.id;
                vm.nocMember.col1 = rowData.col1;
            }

        },
        saveOrUpdCard: function (event) {
            $('#btnSaveOrUpdCard').button('loading').delay(1000).queue(function() {
                var col1 = vm.nocMember.col1;
                var col20 = vm.nocMember.col20;
                var col2 = vm.nocMember.col2;
                var col3 = vm.nocMember.col3;
                console.log(col1);
                var matchReg = new RegExp("^JN-+.{2}-\\d{6}$");  //^JN_*[0-9]{3}$
                //console.log(strMatch.match(matchReg));
                if(!matchReg.test(col20)) {
                    alert("证件编码格式不正确");
                    $('#btnSaveOrUpdCard').button('reset');
                    $('#btnSaveOrUpdCard').dequeue();
                    return ;
                }
                if (!col1.match(/^(13|15|16|18|14|17|19)[0-9]{9}$/)&&col1!='0') {
                //if(col1==null||col1==""){
                    alert("手机号格式不正确！");
                    $('#btnSaveOrUpdCard').button('reset');
                    $('#btnSaveOrUpdCard').dequeue();
                    return ;
                }
                if(col2==null||col2==""){
                    alert("公司不能为空！");
                    $('#btnSaveOrUpdCard').button('reset');
                    $('#btnSaveOrUpdCard').dequeue();
                    return ;
                }
                if(col3==null||col3==""){
                    alert("姓名不能为空！");
                    $('#btnSaveOrUpdCard').button('reset');
                    $('#btnSaveOrUpdCard').dequeue();
                    return ;
                }

                //验证证件编码是否存在
                $.ajax({
                    type: "POST",
                    url: baseURL + "noc/nocmember/userIsExit",
                    contentType: "application/json",
                    data: JSON.stringify(vm.nocMember),
                    success: function(r){
                        if(r.code === 0){
                            layer.alert("证件编码已经存在，请更换！");
                        }else{
                            //会员已经存在
                            var url = "noc/nocmember/saveCard";
                            $.ajax({
                                type: "POST",
                                url: baseURL + url,
                                contentType: "application/json",
                                data: JSON.stringify(vm.nocMember),
                                success: function(r){
                                    if(r.code === 0){
                                        layer.msg("操作成功", {icon: 1});
                                        //清空条件
                                        vm.memberId = vm.nocMember.id;
                                        vm.nocMember = {};
                                        vm.reload();
                                    }else{
                                        layer.alert(r.msg);
                                    }
                                    $('#btnSaveOrUpdCard').button('reset');
                                    $('#btnSaveOrUpdCard').dequeue();
                                }
                            });
                        }
                        $('#btnSaveOrUpdCard').button('reset');
                        $('#btnSaveOrUpdCard').dequeue();


                    }
                });


            });
        },
        //获取展会模板
        /*getTemplates: function () {
            $.ajax({
                type: "POST",
                url: baseURL + "noc/noctemplate/list?limit=100",
                contentType: "application/json",
                data: {},
                success: function(r){
                    if(r.code == 0){
                        vm.templates = r.page.list;
                    }
                }
            });
        },*/
        getLys: function () {
            $.ajax({
                type: "POST",
                url: baseURL + "noc/nocly/list2?limit=1000&tid="+vm.templateId,
                contentType: "application/json",
                data: {},
                success: function(r){
                    if(r.code == 0){
                        vm.lys = r.page.list;
                    }
                }
            });
        },
        getTemplates: function () {
            $.ajax({
                type: "POST",
                url: baseURL + "noc/noctemplate/listByRole",
                contentType: "application/json",
                data: {},
                success: function(r){
                    if(r.code == 0){
                        vm.templates = r.list;
                        vm.getLys();
                    }
                }
            });
        },
        getTemplateTitle: function () {
            vm.colObject = {};
            var colModels = new Array();
            $.ajaxSettings.async = false;
            $.get(baseURL + "noc/noctemplatecol/listAll?limit=100&templateId="+vm.templateId, function(r){
                var jqdata = r.list;

                colModels.push($.parseJSON('{ "label": "id", "name": "id", "index": "id", "width": 50, "key": true }'));
                colModels.push($.parseJSON('{ "label": "签到", "name": "isSign", "index": "is_sign", "width": 50 }'));
                colModels.push($.parseJSON('{ "label": "来源", "name": "ly", "index": "ly", "width": 80 }'));
                for(var i=0;i<jqdata.length;i++){
                    if(jqdata[i].is_show=="1") {
                        colModels.push($.parseJSON('{ "label": "'+jqdata[i].cols_name+'", "name": "col' + jqdata[i].col_id + '", "index": "col' + jqdata[i].col_id + '", "width": '+jqdata[i].width+' }'));
                        vm.colObject['col'+jqdata[i].col_id] = true;
                    }
                }
                colModels.push($.parseJSON('{ "label": "签到时间", "name": "signTime", "index": "signTime", "width": 150 }'));
                colModels.push($.parseJSON('{ "label": "创建时间", "name": "createTime", "index": "create_time", "width": 150 }'));
                colModels.push($.parseJSON('{ "label": "修改人", "name": "updator", "index": "updator", "width": 150 }'));
                colModels.push($.parseJSON('{ "label": "修改时间", "name": "updateTime", "index": "update_time", "width": 150 }'));
            });
            console.log("-------------------");
            console.log(vm.colObject);
            $("#jqBlock").html("");
            $("#jqBlock").append('<table id="jqGrid"></table>');
            $("#jqBlock").append('<div id="jqGridPager"></div>');
            $("#jqGrid").jqGrid({
                url: baseURL + 'noc/nocmember/list',
                datatype: "json",
                colModel: colModels,
                viewrecords: true,
                height: 430,
                rowNum: 10,
                rowList : [10,30,50],
                rownumbers: true,
                rownumWidth: 25,
                autowidth:true,
                multiselect: true,
                shrinkToFit:false,
                autoScroll: true,
                pager: "#jqGridPager",
                jsonReader : {
                    root: "page.list",
                    page: "page.currPage",
                    total: "page.totalPage",
                    records: "page.totalCount"
                },
                prmNames : {
                    page:"page",
                    rows:"limit",
                    order: "order"
                },
                gridComplete:function(){
                    //隐藏grid底部滚动条
                    //$("#jqGrid").closest(".ui-jqgrid-bdiv").css({ "overflow-x" : "hidden" });
                    var ss = vm.getPageSize();
                    $("#jqGrid").jqGrid('setGridWidth', ss.WinW-10).jqGrid('setGridHeight', ss.WinH-130);
                },
                loadComplete: function(data){
                    //设置主活动
                    var obj = $("#jqGrid");
                    var rowIds = obj.getDataIDs();
                    if (rowIds.length > 0) {
                        for (var i = 0; i < rowIds.length; i++) {
                            console.log(obj.getRowData(rowIds[i]));
                            var rowData = obj.getRowData(rowIds[i]);
                            if(rowData.id==vm.memberId){
                                obj.setSelection(rowIds[i]);
                            }
                        }
                    }
                }
            });

            var page = $("#jqGrid").jqGrid('getGridParam','page');
            page = 1;
            $("#jqGrid").jqGrid('setGridParam',{
                postData:{'col1': vm.nocMember.col1,'col2': vm.nocMember.col2,'ly': vm.ly,'templateId':vm.templateId},
                page:page
            }).trigger("reloadGrid");
        },
        getLabels: function () {
            $.ajax({
                type: "POST",
                url: baseURL + "noc/noclabel/list?limit=1000",
                contentType: "application/json",
                data: {},
                success: function(r){
                    if(r.code == 0){
                        vm.nocLabels = r.page.list;
                        //设置默认选中
                        if(vm.selectedLabels){
                            $("input[type='checkbox'][id='cklabel']").each(function() {
                                for(i=0;i<vm.selectedLabels.length;i++){
                                    console.log($(this).val()==vm.selectedLabels[i].labelId);
                                    if($(this).val()==vm.selectedLabels[i].labelId){
                                        console.log("=======");
                                        $(this).prop('checked',true);
                                    }
                                }
                            });
                        }
                    }
                }
            });
        },
	}
});


